package com.accenture.fd.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.accenture.fd.entity.DesignScreenDto;
import com.accenture.fd.entity.DtoToSource;
import com.accenture.fd.entity.OutputDesignDtoData;
import com.accenture.fd.service.DtoSourceService;
import com.accenture.fd.service.OutputDesignService;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.WorkbookUtil;

@CrossOrigin
@RestController
public class OutputDesignController {

	private static final String TEMPLATE_PATH = "/doc/仕様書/ATCC_DTO仕様書_テンプレート.xls"; // 模版路径 (需确认是否放在项目,如果放在项目需要做改动)
	private static final String SHEET_NAME = "DTO仕様書"; // sheet名称
	private static final int LINE_NO = 10; // sheet名称

	@Autowired
	private OutputDesignService outputDesignService;

	@Autowired
	private DtoSourceService dtoSourceService;

	@RequestMapping("/getScreenIdList")
	public List<String> getScreenIdList(HttpServletRequest request) {

		List<String> returnValue = outputDesignService.getScreenIdList();

		return returnValue;
	}

//	@RequestMapping(path = "/getDesignScreenDtoList", method=RequestMethod.GET, consumes= "application/json")
//	public List<DesignScreenDto> getDesignScreenDtoList(@RequestParam String screenId, String filterValue) {
	@RequestMapping("/getDesignScreenDtoList")
	public List<DesignScreenDto> getDesignScreenDtoList(HttpServletRequest request) {

		String screenId  = request.getParameterMap().get("screenId")[0];
		String filterValue = request.getParameterMap().get("filterValue")[0];

		List<DesignScreenDto> designScreenDtoList = outputDesignService.getDesignScreenDtoList(screenId, filterValue);
//		DesignScreenDto designScreenDto = new DesignScreenDto();
//		for (int i = 1; i < 30; i++) {
//			designScreenDto = new DesignScreenDto();
//			designScreenDto.setId(Long.valueOf(i));
//			designScreenDto.setItemId("itemId" + i);
//			designScreenDto.setItemName("項目名" + i);
//			designScreenDto.setItemType("itemType" + i);
//			designScreenDto.setItemGroup("itemGroup" + i);
//			designScreenDto.setItemExplanation("itemExplanation" + i);
//			designScreenDtoList.add(designScreenDto);
//		}

		return designScreenDtoList;
	}


	@RequestMapping("/registerDto")
	public void registerDto(@RequestBody OutputDesignDtoData outputDesignDtoData, HttpServletResponse response,HttpServletRequest request ) {

		String filePath = OutputDesignController.class.getResource(TEMPLATE_PATH).getPath();

		InputStream is = null;
		try {
			String path = URLDecoder.decode(filePath, "UTF-8");
			is = new FileInputStream(new File(path));
			Workbook wb = WorkbookFactory.create(is);
			Sheet sheet = WorkbookUtil.getOrCreateSheet(wb, SHEET_NAME);
			setDetails(outputDesignDtoData, sheet, wb);
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			String name = outputDesignDtoData.getClassNm();
			response.setHeader("Content-Disposition", "attachment;filename=" + "ATCC_DTO仕様書（" + name + "）.xlsx");
			ServletOutputStream out = null;
			out = response.getOutputStream();
			wb.write(out);
			out.flush();
			is.close();
			IoUtil.close(out);

			//DB insert
			String screenId  = request.getParameterMap().get("screenId")[0];
			List<DtoToSource> saveList = new ArrayList<>();
			for (Iterator<DesignScreenDto> iterator = outputDesignDtoData.getListOfData().iterator(); iterator.hasNext();) {
				DesignScreenDto iteminfo = iterator.next();
              if(!iteminfo.getItemId().isEmpty()) {
				DtoToSource dtotoSrc = new DtoToSource();
				dtotoSrc.setClassId(outputDesignDtoData.getClassCd());
				dtotoSrc.setScreenId(screenId);
				dtotoSrc.setClassComment(name);
				dtotoSrc.setCreateStatus("1");
				dtotoSrc.setNameKanji(iteminfo.getItemName());
				dtotoSrc.setNamePhysics(iteminfo.getItemId());
				dtotoSrc.setInterfaceClass("");
				dtotoSrc.setParentClass("");
				saveList.add(dtotoSrc);
              }
			}



			dtoSourceService.deleteDesignDto(screenId);
			dtoSourceService.saveDesignDtoList(saveList);

		} catch (IOException | EncryptedDocumentException | InvalidFormatException e) {
			e.printStackTrace();
		}

	}

	private void setDetails(OutputDesignDtoData outputDesignDtoData, Sheet sheet, Workbook wb) throws IOException {
		// Class 名（日本語）
		sheet.getRow(4).getCell(2).setCellValue(outputDesignDtoData.getClassNm());
		// Class 名（物理）
		sheet.getRow(5).getCell(2).setCellValue(outputDesignDtoData.getClassCd());
		// DTO種類
		sheet.getRow(7).getCell(2).setCellValue("画面DTO");

		// 10行から下の行は動的に移動します
		if (outputDesignDtoData.getListOfData().size() > 0) {
			excelInsertRow(LINE_NO, outputDesignDtoData.getListOfData().size(), sheet);
		}

//		CellStyle cellStyle = wb.createCellStyle();
//
//		cellStyle.setBorderBottom(BorderStyle.THIN);
//		cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
//
//		cellStyle.setBorderLeft(BorderStyle.THIN);
//		cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
//
//		cellStyle.setBorderTop(BorderStyle.THIN);
//		cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
//
//		cellStyle.setBorderRight(BorderStyle.THIN);
//		cellStyle.setRightBorderColor(HSSFColor.BLACK.index);

		//
		int count = 0;
		CellRangeAddress region = null;
		for (int i = 0; i < outputDesignDtoData.getListOfData().size(); i++) {

			DesignScreenDto designScreenDto = outputDesignDtoData.getListOfData().get(i);
			// Line No
			sheet.getRow(LINE_NO + i).getCell(0).setCellValue(i + 1);
			// Field Japanese
			sheet.getRow(LINE_NO + i).getCell(1).setCellValue(designScreenDto.getItemName());
			// Field English
			sheet.getRow(LINE_NO + i).getCell(2).setCellValue(designScreenDto.getItemId());
			// Data Structure
			sheet.getRow(LINE_NO + i).getCell(3).setCellValue(designScreenDto.getStructure());
			// Data Type
			sheet.getRow(LINE_NO + i).getCell(4).setCellValue(designScreenDto.getItemType());
			// Data Structure
			sheet.getRow(LINE_NO + i).getCell(8).setCellValue(designScreenDto.getItemExplanation());

//			if (i == 0) {
//				//フィールド定義を設定
//				sheet.getRow(LINE_NO + i).getCell(1).setCellValue(fld.getFieldDefinition());
//				//フィールド概要を設定
//				sheet.getRow(LINE_NO + i).getCell(4).setCellValue(fld.getFieldSummary());
//				//備考を設定
//				sheet.getRow(LINE_NO + i).getCell(7).setCellValue(fld.getFieldmiddleRemarks());
//			} else {
//				//フィールド定義を設定
//				sheet.getRow(LINE_NO + i).getCell(1).setCellValue(fld.getFieldDefinition());
////				region = new CellRangeAddress(22 + i, 22 + i, 1, 3);
////				sheet.addMergedRegion(region);
//				//フィールド概要を設定
//				sheet.getRow(LINE_NO + i).getCell(4).setCellValue(fld.getFieldSummary());
////				region = new CellRangeAddress(22 + i, 22 + i, 4, 6);
////				sheet.addMergedRegion(region);
//				//備考を設定
//				sheet.getRow(LINE_NO + i).getCell(7).setCellValue(fld.getFieldmiddleRemarks());
////				region = new CellRangeAddress(22 + i, 22 + i, 7, 8);
////				sheet.addMergedRegion(region);
//			}
			//連番を設定
//			if (i == ctmModel.getFieldList().size() - 1) {
//				count = 22 + i;
//				excelInsertRow(count + 1, -1, sheet);
//				excelInsertRow(count + 2, -1, sheet);
//			}

		}
//		//メソッドを設定
//		for (int j = 0; j < ctmModel.getMethodList().size(); j++) {
//
//			MethodListDTO mld = ctmModel.getMethodList().get(j);
//			//連番を設定
//			sheet.createRow(count + 6 + j).createCell(0).setCellValue(j + 1);
//			sheet.createRow(count + 6 + j).getCell(0).setCellStyle(cellStyle);
//			if (j == 0) {
//				//メソッド定義を設定
//				sheet.getRow(count + 6 + j).createCell(1).setCellValue(mld.getMethodDefinition());
//				//メソッド概要を設定
//				sheet.getRow(count + 6 + j).createCell(4).setCellValue(mld.getMethodSummary());
//				//備考を設定
//				sheet.getRow(count + 6 + j).createCell(7).setCellValue(mld.getFootRemarks());
//			} else {
//				//メソッド定義を設定
//				sheet.getRow(count + 6 + j).createCell(1).setCellValue(mld.getMethodDefinition());
//				region = new CellRangeAddress(count + 6 + j, count + 6 + j, 1, 3);
//				sheet.addMergedRegion(region);
//				//メソッド概要を設定
//				sheet.getRow(count + 6 + j).createCell(4).setCellValue(mld.getMethodSummary());
//				region = new CellRangeAddress(count + 6 + j, count + 6 + j, 4, 6);
//				sheet.addMergedRegion(region);
//				//備考を設定
//				sheet.getRow(count + 6 + j).createCell(7).setCellValue(mld.getFootRemarks());
//				region = new CellRangeAddress(count + 6 + j, count + 6 + j, 7, 8);
//				sheet.addMergedRegion(region);
//			}
//			sheet.getRow(count + 6 + j).getCell(1).setCellStyle(cellStyle);
//			sheet.getRow(count + 6 + j).getCell(4).setCellStyle(cellStyle);
//			sheet.getRow(count + 6 + j).getCell(7).setCellStyle(cellStyle);
//		}
	}

	/**
	 * Excel行削除／インサート,上／下の行は動的に移動します
	 * starRow：初めて行
	 * rows：インサート行数
	 * sheet:目標シート
	 */
	private void excelInsertRow(int starRow, int rows, Sheet sheet) {

		if (rows > 0) {
			sheet.shiftRows(starRow + 1, sheet.getLastRowNum(), rows, true, false);
		} else {
			sheet.shiftRows(starRow + 1, starRow + 1, rows);
		}

		starRow = starRow - 1;

		for (int i = 0; i < rows; i++) {
			HSSFRow sourceRow = null;
			HSSFRow targetRow = null;
			HSSFCell sourceCell = null;
			HSSFCell targetCell = null;
			short m;
			starRow = starRow + 1;
			sourceRow = (HSSFRow) sheet.getRow(starRow);
			targetRow = (HSSFRow) sheet.createRow(starRow + 1);
			targetRow.setHeight(sourceRow.getHeight());

			for (m = sourceRow.getFirstCellNum(); m < sourceRow.getLastCellNum(); m++) {
				sourceCell = sourceRow.getCell(m);
				targetCell = targetRow.createCell(m);
				targetCell.setCellStyle(sourceCell.getCellStyle());
			}
		}
	}

//	@PostMapping("/register")
//	public String register(@RequestBody OutputDesignDtoData outputDesignDtoData) {
//
////		OutputDesignDtoData outputDesignDtoData = (outputDesignDtoDataP)request.getParameterMap().get("outputDesignDtoDataP")[0];
////		OutputDesignDtoData outputDesignDtoData  = (OutputDesignDtoData)request.getParameterValues("outputDesignDtoDataP");
//
//		return "";
//	}

//	@PostMapping("/register")
//	public void register(@RequestBody OutputDesignDtoData outputDesignDtoData, HttpServletResponse response) {
//
//		try {
//			XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("C:\\file\\Excel.xlsx"));
//			XSSFSheet sheet = wb.getSheet("Sheet1");
//
//			for (int i = 0; i < 100; i++) {
//
//				XSSFRow row = sheet.createRow(i + 1);
//
//				row.createCell(0).setCellValue("张三" + i);
//				row.createCell(1).setCellValue(i);
//				row.createCell(2).setCellValue("男" + i);
//				row.createCell(3).setCellValue("科研" + i);
//			}
//
//			OutputStream output = response.getOutputStream();
//
//			response.reset();
//			response.setHeader("Content-Disposition", "attchement;filename=" + new String("AAAA.xlsx".getBytes("gb2312"), "ISO8859-1"));
//			response.setContentType("application/msexcel");
//			wb.write(output);
//			wb.close();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

//	@RequestMapping("/exportExcel")
//	  public void exportExcel(HttpServletResponse response) throws IOException {
//		  Workbook workbook = new XSSFWorkbook();
//		  Sheet sheet = workbook.createSheet("new sheet");
//
//		  Row row = sheet.createRow(0);
//		  row.createCell(0).setCellValue("学号");
//		  row.createCell(1).setCellValue("姓名");
//		  row.createCell(2).setCellValue("手机号码");
//
//		  int i = 1;
//		  for (i = 1; i < 20; i++) {
//		    row = sheet.createRow(i);
//		    row.createCell(0).setCellValue("ZZZZZZZZZZZ");
////		    row.createCell(1).setCellValue(student.getName());
////		    row.createCell(2).setCellValue(student.getPhoneNumber());
//		    i++;
//		  }
//
//		  OutputStream fos;
//		  try {
//		    fos = response.getOutputStream();
//
////		    response.reset();
////		    String fileName = "test";
////		    fileName = URLEncoder.encode(fileName, "utf8");
////		    response.setHeader("Content-disposition", "attachment;filename="+ fileName+".xlsx");
////
////		    response.setCharacterEncoding("UTF-8");
////		    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 设置contentType为excel格式
//		    workbook.write(fos);
//		    fos.close();
//
//		  } catch (Exception e) {
//		      e.printStackTrace();
//		  }
//	}

}
